package madixin.t501;


import java.util.ArrayList;
import java.util.List;

class Solution {
    private int curCnt = 1;
    private int maxCnt = 1;
    private TreeNode preNode = null;
    List<Integer> maxCntNums = new ArrayList<>();

    public int[] findMode(TreeNode root) {
        inOrder(root);
        int[] res = new int[maxCntNums.size()];
        for (int i = 0; i < maxCntNums.size(); i++) {
            res[i] = maxCntNums.get(i);
        }
        return res;
    }

    private void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        if (preNode != null) {
            if (preNode.val == root.val){
                curCnt++;
            }
            else{
                curCnt = 1;
            }
        }
        if (curCnt == maxCnt){
            maxCntNums.add(root.val);
        }else if (curCnt > maxCnt){
            maxCntNums.clear();
            maxCnt = curCnt;
            maxCntNums.add(root.val);
        }
        preNode = root;
        inOrder(root.right);
    }
}